package com.visionet.school.app.web.service.wechat;

import com.alibaba.fastjson.JSONObject;
import com.visionet.school.app.web.entity.enums.LoginType;
import com.visionet.school.app.web.entity.enums.MemberType;
import com.visionet.school.app.web.entity.member.Member;
import com.visionet.school.app.web.entity.member.MemberClass;
import com.visionet.school.app.web.entity.member.MemberRel;
import com.visionet.school.app.web.entity.tclass.SchoolClass;
import com.visionet.school.app.web.entity.user.User;
import com.visionet.school.app.web.entity.vo.LoginAccountVo;
import com.visionet.school.app.web.entity.vo.StudentVo;
import com.visionet.school.app.web.repository.member.MemberClassRepository;
import com.visionet.school.app.web.repository.member.MemberRelRepository;
import com.visionet.school.app.web.repository.member.MemberRepository;
import com.visionet.school.app.web.repository.tclass.SchoolClassRepository;
import com.visionet.school.app.web.repository.wechat.MemberLoginRepository;
import com.visionet.school.app.web.wechat.service.bo.JsapiTicketBo;
import com.visionet.school.app.web.wechat.service.bo.TokenBo;
import com.visionet.school.app.web.wechat.utils.DataTransfer;
import com.visionet.school.app.web.wechat.vo.ClientCredentialVO;
import com.visionet.school.app.web.wechat.vo.JsapiTicketVo;
import com.visionet.school.app.web.wechat.vo.MainVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hxpeng on 2017/3/22.
 */
@Service
public class WechatService {

    private static final Logger logger = LoggerFactory.getLogger(WechatService.class);

    @Resource
    private MemberLoginRepository memberLoginRepository;

    @Resource
    private MemberRepository memberRepository;

    @Resource
    private MemberRelRepository memberRelRepository;

    @Resource
    private MemberClassRepository memberClassRepository;

    @Resource
    private SchoolClassRepository schoolClassRepository;

    /***
     * 获取token
     * @return
     */
    @Cacheable(value = "accessTokenCache")
    public TokenBo GetToken(){

        TokenBo token=new TokenBo();
        try {
            String strUrl = MainVO.GetTokenUrl();
            //System.out.println(strUrl);
            String buf = DataTransfer.PostDataToWeiXin(strUrl, null);
            ClientCredentialVO vo = JSONObject.parseObject(buf,ClientCredentialVO.class);
            if (vo.getErrcode() == null || vo.getErrcode() == "") {
                token.setToten(vo.getAccess_token());

            }
        } catch (Exception e) {
            token.setToten(e.getMessage());
        }
        return token;
    }

    /***
     * 通过 code获取用户openid
     * @return
     */
    //@CacheEvict(value="TokenInitService.GetToken")
    public String GetAccessToken(String code){
        String openid="";
        try {
            String strUrl = MainVO.GetOpenID(code);
            //System.out.println(strUrl);
            String buf = DataTransfer.PostDataToWeiXin(strUrl, null);
            JSONObject objjson = JSONObject.parseObject(buf);
            openid= objjson.getString("openid");
        } catch (Exception e) {

        }
        return openid;
    }
    //@CacheEvict(value="TokenInitService.GetToken")
    public String GetAccessTokenString(String code){
        String buf="";
        try {
            String strUrl = MainVO.GetOpenID(code);
            //System.out.println(strUrl);
            buf = DataTransfer.PostDataToWeiXin(strUrl, null);
        } catch (Exception e) {

        }
        return buf;
    }
    /**
     * 通过opendid获取用户信息
     * @param openid
     * @return
     */
    public String GetUserInfo(String accessToken,String openid){
        String userInfo = "";
        try {
            String strUrl = MainVO.GetUserInfo(accessToken,openid);
            System.out.println(strUrl);
            userInfo = DataTransfer.PostDataToWeiXin(strUrl, null);
        } catch (Exception e) {

        }
        return userInfo;
    }
    public String GetMobileUserInfo(String accessToken, String openid) {
        // TODO Auto-generated method stub
        String userInfo = "";

        try {
            String strUrl = MainVO.GetUserInfo(accessToken,openid);
            System.out.println(strUrl);
            userInfo = DataTransfer.PostDataToWeiXin(strUrl, null);

        } catch (Exception e) {

        }
        return userInfo;
    }

    /**
     * 获取jsapiTicket 放入jsapiTicketCache中，7200s过期
     * @return
     */
    @Cacheable(value = "jsapiTicketCache")
    public JsapiTicketBo getJsapiTicket() {
        logger.info("===========================================");
        logger.info("获取微信sdk凭证");
        JsapiTicketBo jsapiTicketBo = new JsapiTicketBo();
        try {
            String strUrl = MainVO.GetJsapiTicket();
            String buf = DataTransfer.PostDataToWeiXin(strUrl, null);
            JsapiTicketVo jsapiTicketVo = JSONObject.parseObject(buf, JsapiTicketVo.class);
            if (jsapiTicketVo.getErrcode().equals("0")) {
                jsapiTicketBo.setJsapiTicket(jsapiTicketVo.getTicket());
            }else{
                throw new RuntimeException("获取微信jsapiticket失败！");
            }
        } catch (Exception e) {
            jsapiTicketBo.setJsapiTicket(e.getMessage());
        }
        return jsapiTicketBo;
    }


    //前端loginAccount在store为空时，调用此请求
    public LoginAccountVo getLoginAccountVo(User user){
        LoginAccountVo loginAccountVo = new LoginAccountVo();
        loginAccountVo.setOpenId(user.getLoginName());
        loginAccountVo.setLoginType(LoginType.WECHAT.toKey());
        loginAccountVo.setMemberParentGender(user.getParentGender());

        //登录账号信息绑定了成员ID和被绑定着的关系。方算绑定过的
        if(StringUtils.isNotBlank(user.getMemberId())){
            Member member = memberRepository.findOne(user.getMemberId());
            member.setAvatarPath(user.getProfile());
            member.setMemberSex(user.getSex());
            memberRepository.save(member);
            if(member != null){
                loginAccountVo.setParentGender(user.getParentGender());
                loginAccountVo.setMemberId(member.getId());
                loginAccountVo.setMemberName(member.getMemberName());
                loginAccountVo.setMemberType(member.getMemberType());
                loginAccountVo.setMemberAvatarPath(member.getAvatarPath());
                //如果登录角色是家长，查询所有他的孩子
                if(member.getMemberType().equals(MemberType.PARENT.toKey())){
                    List<MemberRel> memberRelList = memberRelRepository.findAllStudentByParent(member.getId());
                    logger.info("用户宝宝关系表查询出：" + JSONObject.toJSONString(memberRelList));
                    if(memberRelList != null){
                        List<StudentVo> studentVoList = new ArrayList<>();
                        for(MemberRel memberRel : memberRelList){
                            StudentVo studentVo = new StudentVo();
                            Member student = memberRepository.findOne(memberRel.getMemberId());
                            if(student != null){
                                studentVo.setMemberId(student.getId());
                                studentVo.setMemberName(student.getMemberName());
                                studentVo.setAvatarPath(student.getAvatarPath());
                                MemberClass memberClass = memberClassRepository.findOneByMemberId(student.getId());
                                if(memberClass != null){
                                    SchoolClass schoolClass = schoolClassRepository.findOne(memberClass.getClassId());
                                    if(schoolClass != null){
                                        studentVo.setClassId(schoolClass.getId());
                                        studentVo.setClassName(schoolClass.getClassName());
                                    }
                                    MemberClass teacherClass = memberClassRepository.findTeacherByClassId(memberClass.getClassId());
                                    if(teacherClass != null){
                                        Member teacher = memberRepository.findOne(teacherClass.getMemberId());
                                        if(teacher != null){
                                            studentVo.setTeacherId(teacher.getId());
                                            studentVo.setTeacherName(teacher.getMemberName());
                                        }
                                    }
                                }
                                studentVoList.add(studentVo);
                            }
                            logger.info("用户：" + user.getMemberId() + "查找出学生：" + JSONObject.toJSONString(studentVoList));
                        }
                        loginAccountVo.setStudentVoList(studentVoList);
                    }
                }else if(member.getMemberType().equals(MemberType.TEACHER.toKey())){
                    MemberClass memberClass = memberClassRepository.findOneByMemberId(member.getId());
                    if(memberClass != null){
                        loginAccountVo.setClassId(memberClass.getClassId());
                    }
                }
            }else{
                return null;
            }
        }
        return loginAccountVo;
    }


}
